using System;
using System.Collections;
using UnityEngine;

namespace EventBehaviorTree
{
    [Serializable]
    public class Asynchronous : EventNode
    {
        private Action Action = delegate { };
        private IEnumerator _worker;

        public Asynchronous() { }
        public Asynchronous(Action action) { Action = action; }

        private IEnumerator Worker()
        {
            SeniorNodeEvent(NodeMessage.Success);//the coroutine has been started successfully
            //most probably combines with a countdown sequencer, or a condition sequencer
            //sequencer will start the node one by one after get the success message
            while (true)
            {
                Action();
                yield return null;
            }
        }

        public void SetAction(Action action) { Action = action; }

        private void ResetWorker()
        {
            if (_worker != null)
            {
                _coroutineStarter.StopCoroutine(_worker);
                _worker = null;
            }
            _worker = Worker();
        }

        public override void NodeEvent(NodeMessage nodeMessage)
        {
            switch (nodeMessage)
            {
                case NodeMessage.Start:
                    ResetWorker();
                    _coroutineStarter.StartCoroutine(_worker);
                    return;
                case NodeMessage.COMMAND_Stop:
                    ResetWorker();
                    return;
                default:
                    return;
            }
        }
    }
}
